<template>
  <a-spin :spinning="spinning" class="page-miH">
    <TableTitle v-if="mode === 'company'" style="padding: 0; height: 32px; line-height: 32px; margin: 4px 0 16px">
      <template slot="title">签署记录</template>
      <template slot="action">
        <template v-if="selectTypeIndex === 2">
          <a-button :disabled="!selectedRowKeys.length" @click="signBatch">批量签署</a-button>
          <a-divider type="vertical" style="margin: 0 16px" />
        </template>
        <a-button :disabled="!selectedRowKeys.length" @click="deleteContract()">批量删除</a-button>
        <a-divider type="vertical" style="margin: 0 16px" />
        <a @click="goSetting"> <a-icon type="setting" theme="filled" />设置 </a>
      </template>
    </TableTitle>
    <div class="contract-wrapper">
      <SummaryBarElectronic v-if="mode === 'company'" ref="summaryBar" :selectTypeIndex="selectTypeIndex" @typeChange="selectFunc" />
      <TableBody
        selectHead
        selection
        :tableName="mode === 'overview' ? 'eleContractOV' : 'eleContract'"
        :selectedHead.sync="selectedHead"
        :selectedRowKeys.sync="selectedRowKeys"
        :source="contractList"
        :headerRowID="'sortable_list'"
        :columns="columns"
        :class="mode === 'company' ? 'mt24' : ''"
        @onClose="() => {}"
        @onSearch="selectFunc()"
        @onReload="selectFunc(selectTypeIndex)"
        @onExport="() => selectDownloadType(1)"
        @onExportAll="() => selectDownloadType(2)"
      >
        <template slot="search">
          <a-input-search
            v-model="contractNameOrNoOrSignNo"
            :allowClear="true"
            placeholder="姓名/手机号/合同名称"
            style="width: 220px"
            @search="searchContract"
          />
          <a-select
            v-if="mode === 'overview'"
            v-model="selectTypeIndex"
            placeholder="请选择合同状态"
            style="width: 200px"
            @select="selectFunc"
          >
            <a-select-option :value="4">全部合同</a-select-option>
            <a-select-option :value="1">待员工签署</a-select-option>
            <a-select-option :value="2">待公司签署</a-select-option>
            <a-select-option :value="3">签署完成</a-select-option>
            <a-select-option :value="-1">合同过期未签署</a-select-option>
            <a-select-option :value="5">即将到期</a-select-option>
            <a-select-option :value="6">已到期</a-select-option>
          </a-select>
          <template v-if="mode === 'company'">
            <a-select v-model="fileType" :allowClear="true" placeholder="请选择合同类型" style="width: 200px" @change="searchContract">
              <a-select-option v-for="item in enumerateList" :key="item.value" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="empStatus" :allowClear="true" placeholder="请选择员工状态" style="width: 200px" @change="searchContract">
              <a-select-option value="1">待入职</a-select-option>
              <a-select-option value="2">在职</a-select-option>
              <a-select-option value="3">待离职</a-select-option>
              <a-select-option value="4">离职</a-select-option>
            </a-select>
          </template>
          <template v-else>
            <a-select v-model="fileType" :allowClear="true" label="合同类型" placeholder="请选择合同类型" style="width: 200px">
              <a-select-option v-for="item in enumerateList" :key="item.value" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select v-model="empStatus" :allowClear="true" label="员工状态" placeholder="请选择员工状态" style="width: 200px">
              <a-select-option value="1">待入职</a-select-option>
              <a-select-option value="2">在职</a-select-option>
              <a-select-option value="3">待离职</a-select-option>
              <a-select-option value="4">离职</a-select-option>
            </a-select>
          </template>
          <a-input-search v-model="idCard" label="身份证号" :allowClear="true" placeholder="身份证号" />
          <a-select
            v-if="mode === 'overview'"
            v-model="tempSubject"
            :allowClear="true"
            label="用工单位"
            placeholder="请选择用工单位"
            style="width: 200px"
          >
            <a-select-option v-for="(subItem, index) in tempSubjectOptions" :key="index" :value="subItem.value">
              {{ subItem.label }}
            </a-select-option>
          </a-select>
          <a-range-picker
            v-model="publishDateRange"
            :allowClear="true"
            :placeholder="['合同开始时间', '合同开始时间']"
            label="合同开始时间"
            format="YYYY-MM-DD"
            style="width: 240px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
          <a-range-picker
            v-model="endDateRange"
            :allowClear="true"
            :placeholder="['合同结束时间', '合同结束时间']"
            label="合同结束时间"
            format="YYYY-MM-DD"
            style="width: 240px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
          <a-range-picker
            v-model="signFinishDateRange"
            :allowClear="true"
            :placeholder="['合同签署完成时间', '合同签署完成时间']"
            label="合同签署完成时间"
            format="YYYY-MM-DD"
            style="width: 320px"
          >
            <a-icon slot="suffixIcon" type="clock-circle" />
          </a-range-picker>
          <a-select v-model="isView" :allowClear="true" label="员工是否已查看" placeholder="员工是否已查看" style="width: 200px">
            <a-select-option value="1">已查看</a-select-option>
            <a-select-option value="0">未查看</a-select-option>
          </a-select>
        </template>
        <template slot-scope="prop">
          <a-table
            :class="prop.className"
            :components="prop.components"
            :columns="prop.columns"
            :scroll="{ x: prop.scrollWidth }"
            :customHeaderRow="
              () => {
                return {
                  domProps: {
                    id: prop.headerRowID
                  }
                };
              }
            "
            :data-source="contractList"
            row-key="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange
            }"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <span slot="name" slot-scope="text, record">
              <a-tooltip placement="bottom">
                <template slot="title" v-if="text">
                  <span>{{ text }}</span>
                </template>
                <div class="contractNoOver">
                  {{ text ? text : "--" }}
                </div>
              </a-tooltip>
              <a-icon
                v-if="mode === 'company'"
                type="form"
                style="color: #e8e8e8; font-size: 18px"
                class="ml8"
                @click="updateName(record)"
              />
            </span>
            <span slot="fileType" slot-scope="text">{{ customRenderContractType(text) }}</span>
            <span slot="publishDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="signDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="endDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="empSignDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="signFinishDate" slot-scope="text">{{ customRenderMoment(text) }}</span>
            <span slot="signNo" slot-scope="text">
              <span style="font-size: 12px">{{ text ? text : "--" }}</span>
            </span>
            <span slot="isView" slot-scope="text">
              <span
                v-if="text"
                class="fs12 ta-center"
                style="
                  display: inline-block;
                  background: rgba(50, 204, 170, 0.12);
                  border-radius: 2px;
                  width: 48px;
                  height: 22px;
                  line-height: 22px;
                  color: rgba(17, 174, 139, 1);
                "
                >已查看</span
              >
              <span
                v-else
                class="fs12 ta-center"
                style="
                  display: inline-block;
                  background: rgba(126, 126, 126, 0.12);
                  border-radius: 2px;
                  width: 48px;
                  height: 22px;
                  line-height: 22px;
                  color: rgba(132, 132, 132, 1);
                "
                >未查看</span
              >
            </span>
            <span slot="dateline" slot-scope="text">
              <span style="font-size: 12px">{{ text ? (text % 12 === 0 ? text / 12 + "年" : text + "月") : "--" }}</span>
            </span>
            <span slot="contractNo" slot-scope="text, record">
              <a-tooltip placement="bottom">
                <template slot="title" v-if="text">
                  <span>{{ text }}</span>
                </template>
                <div class="contractNoOver">{{ text ? text : "--" }}</div>
              </a-tooltip>
              <a-icon
                v-if="mode === 'company'"
                type="form"
                style="color: #e8e8e8; font-size: 18px"
                class="ml8"
                @click="updateContactNumber(record)"
              />
            </span>
            <span slot="status" slot-scope="text">
              <span :class="text === 3 ? 'color2294FF' : text === 2 ? 'colorFAC04A' : 'colorC0C0C0'">•</span>
              {{ text === 1 ? "待员工签署" : text === 2 ? "待公司签署" : text === -1 ? "合同过期未签署" : "签署完成" }}
            </span>
            <span slot="partyBName" slot-scope="text">{{ text }}</span>
            <span slot="remainingValidTime" slot-scope="text">
              <span :class="text === 3 ? 'color2294FF' : text === 2 ? 'colorFAC04A' : 'colorC0C0C0'">
                <a-icon
                  v-if="text <= 30 && text >= 0 && text !== null"
                  type="exclamation-circle"
                  :style="{ fontSize: '16px', color: '#FA5051' }"
                />
              </span>
              <span :style="text <= 30 && text >= 0 && text !== null ? 'color: #FA5051' : ''" v-if="text >= 0 && text !== null"
                >{{ text }} 天</span
              >
              <span v-else-if="text === null" style="color: #909090">--</span>
              <span v-else style="color: #909090">已到期</span>
            </span>
            <span slot="appIsShow" slot-scope="text, record">
              <a-switch
                checked-children="是"
                un-checked-children="否"
                :disabled="mode !== 'company'"
                :default-checked="record.appIsShow"
                @change="changeUsed($event, record)"
              />
            </span>
            <span slot="action" slot-scope="text, record">
              <span
                class="flex-center"
                :style="{
                  width: selectTypeIndex === 2 && mode === 'company' ? 120 : 80
                }"
              >
                <template v-if="mode === 'company'">
                  <a v-if="selectTypeIndex === 2" v-onceClick class="edit" type="link" @click="confirmSign(record)">确认签署</a>
                  <a-divider v-if="selectTypeIndex === 2" type="vertical" />
                </template>
                <a class="edit" type="link" @click="check(record)">预览</a>
              </span>
            </span>
          </a-table>
        </template>
      </TableBody>
      <!-- 导出合同 -->
      <a-modal v-model="editVisible" :title="exportContractTitle" footer>
        <div style="margin-bottom: 24px">*请选择合同导出样式</div>
        <div class="staff-top-dialog">
          <a-button class="staff-one" @click="pdf_export">
            <div class="staff-top-dialog-item">
              <div>导出电子合同PDF文件</div>
              <img style="width: 18px; height: 18px" src="@/assets/img/arrow.png" />
            </div>
          </a-button>
          <a-button class="staff-one" @click="excel_export">
            <div class="staff-top-dialog-item">
              <div>导出电子合同详情列表</div>
              <img style="width: 18px; height: 18px" src="@/assets/img/arrow.png" />
            </div>
          </a-button>
        </div>
      </a-modal>
      <!-- 预览合同 -->
      <a-modal
        title="预览"
        :confirm-loading="confirmLoading"
        :visible="detailVisible"
        width="800px"
        @ok="(detailVisible = false), (eleContractDetailShow = false)"
        @cancel="(detailVisible = false), (eleContractDetailShow = false)"
      >
        <div class="flex-start-center">
          <iframe
            v-if="eleContractDetailShow"
            :src="`${eleContractDetail.path}?token=${auth.token}`"
            class="checkbox"
            style="width: 700px; height: 70vh; overflow: auto"
          />
        </div>
      </a-modal>
      <!-- 编辑合同 -->
      <a-modal
        title="编辑合同备注"
        :visible="updateVisible"
        :confirm-loading="confirmLoading"
        @ok="confirmUpdateContactNumber"
        @cancel="handleCancel"
      >
        <div>
          <a-form :form="updateForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" :colon="true">
            <a-form-item label="合同名称" v-show="false">
              <a-input style="width: 100%" placeholder="请输入" allowClear v-decorator="['name']" />
            </a-form-item>
            <a-form-item label="合同备注">
              <a-textarea
                style="width: 100%"
                placeholder="请输入"
                allowClear
                :maxLength="255"
                :auto-size="{ minRows: 8, maxRows: 15 }"
                v-decorator="['contractNo']"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <a-modal
        title="编辑合同名称"
        :visible="updateNameVisible"
        :confirm-loading="confirmNameLoading"
        @ok="confirmUpdateName"
        @cancel="handleNameCancel"
      >
        <div>
          <a-form :form="updateNameForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" :colon="true">
            <a-form-item label="合同名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '已签署的合同名称不能为空' }]
                  }
                ]"
                :maxLength="80"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <!-- 删除合同 -->
      <a-modal
        title="删除合同"
        :visible="deleteVisible"
        class="notice-modal"
        width="468px"
        :okButtonProps="{ props: { disabled: loading_delete } }"
        @ok="confirmDelete"
        @cancel="deleteVisible = false"
      >
        <div class="deleteline">
          <p><a-icon type="exclamation-circle" />确定删除该合同？</p>
        </div>
      </a-modal>
    </div>
  </a-spin>
</template>
<script>
import moment from "moment";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
const mixin = new ExportMixin();
import { mapGetters } from "vuex";
import {
  selectContractPageReq,
  downloadElectronicReq,
  exportAllEleContractReq,
  deleteContractAndRelationByIdReq,
  deleteContractBatchReq,
  contractAppendixReq,
  enterpriseSignReq,
  enterpriseSignBatchReq
} from "./api";
import { mapState } from "vuex";
import { isContainByString } from "@/utils/index";
import { updateContractNoById, updateAppShowById, setJpgToAppendix, putUpdateContractName } from "@/api/company/contract";
import { buildColumns, enumerateList, customRenderContractType, customRenderMoment } from "./funcs";
import SummaryBarElectronic from "./components/summaryBar_electronic.vue";

export default {
  components: { SummaryBarElectronic },
  mixins: [mixin],
  props: {
    mode: {
      type: String,
      default: "company"
    }
  },
  data() {
    const columns = buildColumns("electronic", this.mode === "overview");
    return {
      isContainByString,
      editVisible: false,
      exportContractTitle: "",
      selectedRowList: [],
      columns,
      enumerateList,
      searchForm: this.$form.createForm(this),
      companyName: this.$store.state.hr.companyName,
      updateForm: this.$form.createForm(this, { name: "updateForm" }),
      selectedRowKeys: [],
      contractList: [],
      updateVisible: false,
      detailVisible: false,
      confirmLoading: false,
      deleteVisible: false,
      currentContract: {},
      eleContractDetail: {},
      eleContractDetailShow: false,
      selectTypeIndex: 4,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      spinning: false,
      selectedHead: [],
      updateNameForm: this.$form.createForm(this, {}),
      updateNameVisible: false,
      confirmNameLoading: false,
      putUpdateContractNameId: "",
      // 搜索条件
      contractNameOrNoOrSignNo: "",
      idCard: "",
      fileType: undefined,
      empStatus: undefined,
      publishDateRange: null,
      endDateRange: null,
      signFinishDateRange: null,
      tempSubject: undefined,
      loading_delete: false,
      isView: undefined
    };
  },
  computed: {
    ...mapGetters(["permissions_site"]),
    ...mapState(["auth", "site", "hr"]),
    siteName() {
      return this.auth.siteName;
    },
    companyId() {
      return this.hr.companyId;
    },
    targetIds() {
      if (this.mode === "company") {
        return [this.companyId];
      } else {
        if (this.site.selectAllIds && this.site.selectAllIds !== "-1") {
          return Array.from(new Set(this.site.selectAllIds.split(",")));
        }
        return [];
      }
    },
    tempSubjectOptions() {
      return this.targetIds
        .map((item) => ({
          value: item,
          label: this.hr.companyMap[item] ? this.hr.companyMap[item].name : undefined
        }))
        .filter((item) => item.label);
    }
  },
  watch: {
    $route: {
      handler(to, from) {
        if (this.mode === "company") {
          if (this.$route.query.immediatelyMaturityCountId) {
            // 消息推送进来
            this.$nextTick(() => {
              this.searchForm.setFieldsValue({
                contractNameOrNoOrSignNo: this.$route.query.contractNameOrNoOrSignNo
              });
            });
            this.selectTypeIndex = Number(this.$route.query.immediatelyMaturityCountId);
            this.searchContract(this.$route.query.contractNameOrNoOrSignNo);
          } else {
            this.selectFunc(4);
          }
        }
      },
      deep: true,
      immediate: true
    },
    targetIds() {
      this.tempSubject = undefined;
      this.selectFunc();
    }
  },
  created() {},
  methods: {
    customRenderContractType,
    customRenderMoment,
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadContractList();
    },
    searchContract() {
      this.pagination.current = 1;
      this.loadContractList();
    },
    selectFunc(typeIndex) {
      this.pagination.current = 1;
      this.selectedRowKeys = [];
      if (typeIndex || typeIndex === 0) {
        this.selectTypeIndex = typeIndex;
      }
      if (this.$refs.summaryBar) {
        this.$refs.summaryBar.loadData();
      }
      this.loadContractList();
    },
    loadContractList() {
      if (this.spinning) {
        return false;
      }
      this.spinning = true;
      const params = {
        ...this.buildParams(),
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      selectContractPageReq(params)
        .then((res) => {
          this.spinning = false;
          this.contractList = res.data.entities ? res.data.entities : [];
          this.pagination.total = res.data && res.data.entityCount;
        })
        .catch((err) => {
          this.spinning = false;
          console.log(err);
        });
    },
    onSelectChange(selectedRowKeys, tList) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowList = tList;
    },
    check(record) {
      this.detailVisible = true;
      this.checkEleContract(record.id);
    },
    checkEleContract(id) {
      contractAppendixReq({ contractId: id }).then((res) => {
        this.eleContractDetail = res.data[0];
        this.$nextTick(() => {
          this.eleContractDetailShow = true;
        });
      });
    },
    handleCancel() {
      this.updateVisible = false;
      this.updateForm.resetFields();
    },
    handleNameCancel() {
      this.updateNameVisible = false;
      this.confirmNameLoading = false;
      this.updateNameForm.resetFields();
    },
    updateName(r) {
      this.putUpdateContractNameId = r.id;
      setTimeout(() => {
        this.updateNameForm.setFieldsValue({
          name: r.name
        });
      });
      this.updateNameVisible = true;
    },
    updateContactNumber(record) {
      this.updateVisible = true;
      this.currentContract = record;
      setTimeout(() => {
        this.updateForm.setFieldsValue({
          contractNo: record.contractNo,
          name: record.name
        });
      });
    },
    confirmUpdateName(e) {
      e.preventDefault();
      this.updateNameForm.validateFields((err, values) => {
        if (!err) {
          this.confirmNameLoading = true;
          putUpdateContractName({ id: this.putUpdateContractNameId, name: values.name })
            .then(() => {
              this.updateNameVisible = false;
              this.confirmNameLoading = false;
              this.$message.success("编辑成功");
              this.loadContractList();
            })
            .catch((err) => {
              console.log("error log --> ", err);
              this.confirmNameLoading = false;
            });
        }
      });
    },
    confirmUpdateContactNumber(e) {
      var that = this;
      e.preventDefault();
      this.updateForm.validateFields((err, values) => {
        if (!err) {
          updateContractNoById({
            id: this.currentContract.id,
            contractNo: values.contractNo || "",
            name: values.name || "未命名合同"
          }).then((res) => {
            that.updateVisible = false;
            that.updateForm.resetFields();
            that.$message.success("编辑成功");
            that.loadContractList();
          });
        }
      });
    },
    changeUsed(e, record) {
      updateAppShowById(record.id, e).then((res) => {
        this.$message.success("操作成功");
        this.loadContractList();
      });
    },
    goSetting() {
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/contract-set`
      });
    },
    deleteContract(record) {
      this.currentNotice = record;
      this.deleteVisible = true;
      if (record) {
        this.selectedRowKeys = [];
        this.selectedRowKeys.push(record.id);
      }
    },
    confirmDelete() {
      if (this.contractList.length === this.selectedRowKeys.length && this.pagination.current > 1) {
        this.pagination.current -= 1;
      }
      this.loading_delete = true;
      if (this.selectedRowKeys.length < 1) {
        deleteContractAndRelationByIdReq(this.currentNotice.id)
          .then(() => {
            this.deleteVisible = false;
            this.loading_delete = false;
            this.$message.success("删除成功");
            if (this.$refs.summaryBar) {
              this.$refs.summaryBar.loadData();
            }
            this.loadContractList();
            this.selectedRowKeys = [];
          })
          .catch(() => {
            this.loading_delete = false;
            this.$message.error("删除失败");
          });
      } else {
        deleteContractBatchReq(this.selectedRowKeys)
          .then(() => {
            this.deleteVisible = false;
            this.loading_delete = false;
            this.$message.success("删除成功");
            if (this.$refs.summaryBar) {
              this.$refs.summaryBar.loadData();
            }
            this.loadContractList();
            this.selectedRowKeys = [];
          })
          .catch(() => {
            this.loading_delete = false;
            this.$message.error("删除失败");
          });
      }
    },
    signBatch() {
      if (this.selectedRowKeys.length > 0) {
        try {
          let companySignId = null;
          const firstOne = this.contractList.find((item) => {
            return item.id === this.selectedRowKeys[0];
          });
          firstOne.partySignAccountList.forEach((item) => {
            // 签署公司印章id
            if (item.type === 2) {
              companySignId = item.memberId;
            }
          });
          enterpriseSignBatchReq({
            companyId: companySignId,
            contractIds: this.selectedRowKeys
          })
            .then((res) => {
              if (res && res.success) {
                this.$message.success("签署任务发起成功");
              } else {
                this.$message.success(res.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } catch (error) {
          console.log(error);
        }
      }
    },
    // 企业确认签署
    confirmSign(record) {
      let companySignId = null;
      record.partySignAccountList.forEach((item) => {
        // 签署公司印章id
        if (item.type === 2) {
          companySignId = item.memberId;
        }
      });
      this.spinning = true;
      enterpriseSignReq({
        companyId: companySignId,
        contractId: record.id
      })
        .then((res) => {
          this.$message.success("签署成功");
          this.spinning = false;
          this.loadContractList();
          setJpgToAppendix(record.id)
            .then((res) => {
              if (this.$refs.summaryBar) {
                this.$refs.summaryBar.loadData();
              }
            })
            .catch((err) => {
              console.log("error log --> ", err);
            });
        })
        .catch((err) => {
          this.spinning = false;
          console.log("error log --> ", err);
        });
    },
    buildParams() {
      const params = {
        subjectIds: this.tempSubject ? [this.tempSubject] : this.targetIds,
        contractType: 1,
        status: this.selectTypeIndex > 3 ? null : this.selectTypeIndex,
        contractNameOrNoOrSignNo: this.contractNameOrNoOrSignNo,
        idCard: this.idCard,
        fileType: this.fileType,
        empStatus: this.empStatus,
        isView: this.isView ? this.isView === "1" : null,
        publishDateStart:
          this.publishDateRange && this.publishDateRange.length > 0 ? moment(this.publishDateRange[0]).format("YYYY-MM-DD 00:00:00") : null,
        publishDateEnd:
          this.publishDateRange && this.publishDateRange.length > 0 ? moment(this.publishDateRange[1]).format("YYYY-MM-DD 23:59:59") : null,
        endDateStart: this.endDateRange && this.endDateRange.length > 0 ? moment(this.endDateRange[0]).format("YYYY-MM-DD 00:00:00") : null,
        endDateEnd: this.endDateRange && this.endDateRange.length > 0 ? moment(this.endDateRange[1]).format("YYYY-MM-DD 23:59:59") : null,
        signFinishDateStart:
          this.signFinishDateRange && this.signFinishDateRange.length > 0
            ? moment(this.signFinishDateRange[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        signFinishDateEnd:
          this.signFinishDateRange && this.signFinishDateRange.length > 0
            ? moment(this.signFinishDateRange[1]).format("YYYY-MM-DD 23:59:59")
            : null
      };
      if (this.selectTypeIndex === 5) {
        params["willExpire"] = true;
      }
      if (this.selectTypeIndex === 6) {
        params["alreadyExpire"] = true;
      }
      return params;
    },
    selectDownloadType(i) {
      this.exportType = i;
      this.editVisible = true;
      if (i === 1) {
        this.exportContractTitle = "批量电子合同导出";
      } else {
        this.exportContractTitle = "全部电子合同导出";
      }
    },
    pdf_export() {
      this.spinning = true;
      this.editVisible = false;
      const contractDownloadDTO =
        this.exportType === 1
          ? {
              subjectIds: this.tempSubject ? [this.tempSubject] : this.targetIds,
              contractIdList: this.selectedRowKeys,
              zipName: this.auth.siteName + "电子合同导出记录" + ".zip"
            }
          : {
              ...this.buildParams(),
              zipName: this.auth.siteName + "电子合同导出记录" + ".zip"
            };
      downloadElectronicReq(contractDownloadDTO)
        .then((res) => {
          this.spinning = false;
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            try {
              if (this.selectedRowKeys.length === 1) {
                link.download = `${this.selectedRowList[0].name}(${
                  this.selectedRowList[0].idCard !== undefined ? this.selectedRowList[0].idCard : "身份证号未填写"
                }).pdf`;
              } else if (this.contractList.length === 1) {
                link.download = `${this.contractList[0].name}(${
                  this.contractList[0].idCard !== undefined ? this.contractList[0].idCard : "身份证号未填写"
                }).pdf`;
              } else {
                link.download = `${this.$store.state.hr.companyName}_` + "电子合同导出记录.zip";
              }
            } catch (err) {
              console.log("error log --> ", res);
            }
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("error log --> ", err);
          this.spinning = false;
        });
    },
    excel_export() {
      this.spinning = true;
      this.editVisible = false;
      const contractExcelDTO =
        this.exportType === 1
          ? {
              subjectIds: this.tempSubject ? [this.tempSubject] : this.targetIds,
              exportColumns: this.selectedHead,
              contractIdList: this.selectedRowKeys
            }
          : {
              ...this.buildParams(),
              exportColumns: this.selectedHead,
              signNoOrContractNameOrEmpIdOrEmpPhone: this.contractNameOrNoOrSignNo
            };
      exportAllEleContractReq(contractExcelDTO)
        .then((res) => {
          const data = res.data;
          const url = URL.createObjectURL(data);
          const link = document.createElement("a");
          link.href = url;
          link.download = `${this.mode === "overview" ? this.siteName : this.companyName}合同列表详情.xlsx`;
          link.click();
          this.spinning = false;
        })
        .catch((err) => {
          console.log("error log --> ", err);
          this.spinning = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
